package com.iatinspur.config.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author lxk
 * @Date 2023 06 07 14 10
 **/

//@Component("myThread")
public class ThreadPoolExecutorWrapper {

    Logger logger = LoggerFactory.getLogger(ThreadPoolExecutorWrapper.class.getName());

    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public ThreadPoolExecutorWrapper(){
        int core = Runtime.getRuntime().availableProcessors();
        logger.info("正在创建线程池ThreadPoolTaskExecutor，线程池核心数量：{}", core);
        threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(core);
        threadPoolTaskExecutor.setMaxPoolSize(100);
       // threadPoolTaskExecutor.setTaskDecorator(new MdcTaskDecorator());
        //threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
        threadPoolTaskExecutor.setKeepAliveSeconds(60 * 30);
        threadPoolTaskExecutor.setQueueCapacity(5000);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        threadPoolTaskExecutor.initialize();
        logger.info("线程创建结束，线程池核心数量：{}", core);

    }

    public void executor(Runnable runnable){
        threadPoolTaskExecutor.execute(runnable);
    }

    public Future<?> submit(Runnable runnable){
        Future<?> submit = threadPoolTaskExecutor.submit(runnable);
        return submit;
    }

    public Future<?> submit(Callable<?> task){
        Future<?> submit = threadPoolTaskExecutor.submit(task);
        return submit;
    }


    public ThreadPoolTaskExecutor getThreadPoolExecutor() {
        return threadPoolTaskExecutor;
    }
}
